package com.example.test.activity;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.zip.Inflater;

import com.ant.liao.GifView;
import com.example.test.R;
import com.example.test.R.id;
import com.example.test.R.layout;
import com.example.test.activity.PullDownView.OnPullDownListener;
import com.example.test.model.Constants;
import com.example.test.model.FollowBoolean;
import com.example.test.model.FormatTools;
import com.example.test.model.ImageFactory;
import com.example.test.model.SameFollowProcess;
import com.example.test.model.StatusTextProcess;
import com.example.test.model.imgdown.AsyncDownHeadImageTask;
import com.example.test.model.imgdown.AsyncDownHeadImgTask;
import com.example.test.model.imgdown.AsyncDownStatusImageTask;
import com.example.test.model.json_analyzer.HashDataProcessor;
import com.example.test.model.json_analyzer.SinaJsonAnalyzer;
import com.example.test.model.social_api.NetAPI;
import com.example.test.model.social_api.QQAPI;
import com.example.test.model.social_api.RennAPI;
import com.example.test.model.social_api.SinaAPI;
import com.example.test.model.social_api.SohuWeiboAPI;
import com.netease.microblog.http.blogapi.NeteaseApi;
import com.sina.weibo.sdk.openapi.legacy.StatusesAPI;
import com.sohu.microblog.http.blogapi.SohuApi;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXTextObject;
import com.tencent.weibo.sdk.android.api.WeiboAPI;
import com.tencent.weibo.sdk.android.model.AccountModel;
import com.tencent.weibo.sdk.android.model.ModelResult;
import com.tencent.weibo.sdk.android.network.HttpCallback;
import com.tencent.weibo.sdk.android.model.GlobalVar;

import android.R.drawable;
import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("NewApi")
public class FriLineActivity extends Activity implements OnPullDownListener{

	private ListView lvTimeline=null;
    private PullDownView mPullDownView;
	
	 List<HashMap<String, String>> lArrTimeline = null;
	 HashMap<String, List<byte[]>> mapImgList=new HashMap<String, List<byte[]>>();
	 HashMap<String, List<String>> mapTypeList=new HashMap<String, List<String>>();
	 HashMap<String, Drawable> mapHeadImgList=new HashMap<String,Drawable>();
	 Bitmap loading =null;
	TimeLineAdapter adapter;
	String eQQTimeStamp="";
	String sinaMaxId="";
	String netMaxId="";
	String sohuMaxId="";
	String activity_type="";
	int lastPos=0;
	 Handler handler=new Handler()
	{

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg.what==Constants.MSG_DOWNIMG_SUCCESS)
			{
				HashMap<String, Object> map=(HashMap<String, Object>)msg.obj;
				String position=(String)map.get("position");
				mapHeadImgList.put(position, (Drawable)map.get("img"));
				adapter.notifyDataSetChanged();
			}
			else if(msg.what==Constants.MSG_GETTIMELINE_SUCCESS)
			{
				mPullDownView.notifyDidLoad();
				mPullDownView.notifyDidRefresh();
				mPullDownView.notifyDidMore();
				List<HashMap<String,String>> tempList =(List<HashMap<String,String>>)msg.obj;
				HashDataProcessor.timelineDataProcess(tempList);

				if(tempList.size()!=0)
				{
					judgeOnMoreFirst(tempList);
				}
				setPageInfo(tempList);
				startDownStatusImg(tempList);
				if(lArrTimeline==null)
				{
				lArrTimeline=tempList;
				}
				else
				{
				lArrTimeline.addAll(tempList);
				}
				Collections.sort(lArrTimeline,new StatusListComparator());
				if(adapter==null)
				{
					adapter=new TimeLineAdapter(FriLineActivity.this,handler, lArrTimeline);
				    lvTimeline.setAdapter(adapter);
				}
				else
					adapter.notifyDataSetChanged();
				
		        mPullDownView.enableAutoFetchMore(true, 1);
		       for(int i=0;i<tempList.size();i++)
		       {
		       Thread thread=new Thread(new AsyncDownHeadImgTask(handler, tempList.get(i).get("resource")+tempList.get(i).get("id"), tempList.get(i).get("userprofile_image_url")));
		       thread.start();
		       }
			}
			else if(msg.what==Constants.MSG_REPOST_SUCCESS)
			{
				
				Toast.makeText(FriLineActivity.this, "转发成功", 1000).show();
			}
			else if(msg.what==Constants.MSG_REPOST_FAIL)
			{
				Toast.makeText(FriLineActivity.this, "转发失败:", 1000).show();
			}
			else if(msg.what==Constants.MSG_COMMENT_SUCCESS)
			{
				
				Toast.makeText(FriLineActivity.this, "评论成功", 1000).show();
			}
			else if(msg.what==Constants.MSG_COMMENT_FAIL)
			{
				Toast.makeText(FriLineActivity.this, "评论失败:", 1000).show();
			}
			else if(msg.what==Constants.MSG_DOWNSTATUSIMG_SUCCESS)
			{
				HashMap<String, Object> map=(HashMap<String, Object>)msg.obj;
				String id=(String)map.get("id");
				String [] temp=id.split("_");
				Log.v("test", mapImgList.get(temp[0]+"_"+temp[1]).size()+"    "+temp[2]+"   "+temp[0]+"_"+temp[1]);
				mapImgList.get(temp[0]+"_"+temp[1]).set(Integer.parseInt(temp[2]), (byte[])map.get("img"));
				mapTypeList.get(temp[0]+"_"+temp[1]).set(Integer.parseInt(temp[2]), (String)map.get("type"));
				adapter.notifyDataSetChanged();
			}
		}
		
	};
	
	private void judgeOnMoreFirst(List<HashMap<String,String>> tempList)
	{
		String resource=tempList.get(0).get("resource");
		String id=tempList.get(0).get("id");
		if((resource.equals("sina")&&id.equals(sinaMaxId))||(resource.equals("sohu")&&id==sohuMaxId)||(resource.equals("netease")&&id==netMaxId))
	    tempList.remove(0);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Intent intent =getIntent();
		activity_type = intent.getStringExtra("activity_type");
		if(activity_type.equals("FriTimeline"))
		{
			setContentView(R.layout.activity_friline_main);
		}
		else if(activity_type.equals("NoticeMe"))
		{
			setContentView(R.layout.activity_friline);
		}
		  mPullDownView = (PullDownView) findViewById(R.id.pull_down_view);
	        mPullDownView.setOnPullDownListener(this);
	        lvTimeline = mPullDownView.getListView();
        GlobalVar.changed=true;
        WindowManager wm =getWindowManager();
    	int width = wm.getDefaultDisplay().getWidth();
    	loading=BitmapFactory.decodeResource(getResources(), R.drawable.loading);
    	loading=ImageFactory.scaleImg(width/3-10, width/3-10, loading);
	}
	
	
	
	@Override
	protected void onResume() {
		if(GlobalVar.changed)
		{
			if(lArrTimeline!=null)
			{
				lArrTimeline.clear();
				adapter.notifyDataSetChanged();
			}
			
			if(activity_type.equals("FriTimeline"))
			{
				setWriStatusClick();
				
			 
			      
			    QQAPI.getFriendline(this,handler,0,"0");
				SinaAPI.getFriendline(handler,"0");
				RennAPI.getFriline(handler);
				NetAPI.getFriendline(handler,"0",5);
				SohuWeiboAPI.getFriendline(handler,"0",5);
			}
			else if(activity_type.equals("NoticeMe"))
			{
				
				SinaAPI.getNoticeMeline(handler,"0",5);
				QQAPI.getMentionline(this, handler, 0, "0", 5);
				NetAPI.getMentionLine(handler,"0",5);
				SohuWeiboAPI.getMentionLine(handler,"0",5);
			}
			GlobalVar.changed=false;
		}
		super.onResume();
	}
	@Override
    public void onRefresh() {
		 if(activity_type.equals("FriTimeline"))
		 {
			 QQAPI.getFriendline(this, handler, 0, "0");
		SinaAPI.getFriendline(handler, "0");
		NetAPI.getFriendline(handler, "0", 5);
		SohuWeiboAPI.getFriendline(handler, "0", 5);
		
		 }
		 else if(activity_type.equals("NoticeMe"))
		 {
			 QQAPI.getMentionline(this, handler, 0, "0",5); 
			 SinaAPI.getNoticeMeline(handler, "0", 5);
			 NetAPI.getMentionLine(handler, "0", 5);
			 SohuWeiboAPI.getMentionLine(handler,"0",5);
		 }
		 lArrTimeline.clear();
    }
 
    @Override
    public void onMore() {
    	if(activity_type.equals("FriTimeline"))
    	{
    	if(!eQQTimeStamp.equals(""))
       QQAPI.getFriendline(this, handler, 1, eQQTimeStamp);
    	else
    	QQAPI.getFriendline(this, handler, 0, "0");
    	if(!sinaMaxId.equals(""))
    	       SinaAPI.getFriendline(handler, sinaMaxId);
    	else
    	       SinaAPI.getFriendline(handler, "0");
    	if(!netMaxId.equals(""))
 	       NetAPI.getFriendline(handler, netMaxId,5);
 	   else
 	       NetAPI.getFriendline(handler, "0",5);
    	if(!sohuMaxId.equals(""))
  	       SohuWeiboAPI.getFriendline(handler, sohuMaxId,5);
  	   else
  	       SohuWeiboAPI.getFriendline(handler, "0",5);
    	}
    	else if(activity_type.equals("NoticeMe"))
    	{
    		if(!eQQTimeStamp.equals(""))
    		       QQAPI.getMentionline(this, handler, 1, eQQTimeStamp, 5);
    		 else
    			 QQAPI.getMentionline(this, handler, 0, "0", 5);
    		if(!sinaMaxId.equals(""))
 		       SinaAPI.getNoticeMeline(handler, sinaMaxId, 5);
 		 else
 			SinaAPI.getNoticeMeline(handler, "0", 5);
    		if(!netMaxId.equals(""))
  		       NetAPI.getMentionLine(handler, netMaxId, 5);
  		 else
  			NetAPI.getMentionLine(handler, "0", 5);
    		if(!sohuMaxId.equals(""))
   		       SohuWeiboAPI.getMentionLine(handler, sohuMaxId, 5);
   		 else
   			SohuWeiboAPI.getMentionLine(handler, "0", 5);
    	}
    }
	
	
	 private void startDownStatusImg(List<HashMap<String,String>> tempList)
	 {
		 int i=0;
			for (HashMap<String, String> hashMap : tempList) {
				if(tempList.get(i).get("resource").equals("netease"))
				{
					System.out.println("");
				}
				String id;
				String retid="";
				String images;
				String retimages="";
				id=tempList.get(i).get("resource")+"_"+tempList.get(i).get("id");
				images=hashMap.get("images");
				if(hashMap.get("retweeted_statusid")!=null)
				{
				retid=tempList.get(i).get("resource")+"_"+tempList.get(i).get("retweeted_statusid");
				retimages=hashMap.get("retweeted_statusimages");
				}
				List<byte[]> imgList=new LinkedList<byte[]>();
				List<String> typeList=new LinkedList<String>();
				if(!images.equals("")&&mapImgList.get(id)==null)
				{
					String []arrUrl=images.split(",");
					
					int j=0;
					for (String string : arrUrl) {
						byte[] drawable=null;
						imgList.add(drawable);
						typeList.add("jpg");
			Thread thread=new Thread(new AsyncDownStatusImageTask(handler, id+"_"+j,string));
			thread.start();
						j++;
					}
					
					
				}
				if(mapImgList.get(id)==null)
				{
				mapImgList.put(id, imgList);
				mapTypeList.put(id, typeList);
				}
				if(mapImgList.get(retid)==null)
				{
				List<byte[]> imgRetList=new LinkedList<byte[]>();
				List<String> RettypeList=new LinkedList<String>();
				if(!retimages.equals("")&&mapImgList.get(retid)==null)
				{
					String []arrUrl=retimages.split(",");
					
					int j=0;
					for (String string : arrUrl) {
						byte[] drawable=null;
						imgRetList.add(drawable);
						RettypeList.add("type");
			Thread thread=new Thread(new AsyncDownStatusImageTask(handler, retid+"_"+j,string));
			thread.start();
						j++;
					}
					
                    mapTypeList.put(retid, RettypeList);
					mapImgList.put(retid, imgRetList);
				}
				}
				i++;
			}
	 }
	private void setPageInfo(List<HashMap<String,String>> tempList)
	{
		if(tempList==null)
			return;
		if(tempList.get(0).get("resource").equals("QQ"))
		{
			eQQTimeStamp=tempList.get(tempList.size()-1).get("timestamp");
		}
		else if(tempList.get(0).get("resource").equals("sina"))
		{
			sinaMaxId=tempList.get(tempList.size()-1).get("id");
		}
		else if(tempList.get(0).get("resource").equals("netease"))
		{
			netMaxId=tempList.get(tempList.size()-1).get("cursor_id");
		}
		else if(tempList.get(0).get("resource").equals("sohu"))
		{
			sohuMaxId=tempList.get(tempList.size()-1).get("id");
		}
	}
	 
	private void setWriStatusClick()
	{
		Button btWriStu =(Button)findViewById(R.id.btwristatus);
		btWriStu.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final EditText etWriContent =(EditText) findViewById(R.id.etwricontent);
				String Content =etWriContent.getText().toString();
				/*QQAPI.sendWeibo(Content, FriLineActivity.this);
				SinaAPI.sendWeibo(Content);
				RennAPI.sendWeibo(Content);
				NetAPI.sendWeibo(Content);
				SohuWeiboAPI.sendWeibo(Content);*/
				IWXAPI api=WXAPIFactory.createWXAPI(FriLineActivity.this, "wxd16a1b04206cf9c1",true);
				api.registerApp("wxd16a1b04206cf9c1");
				WXTextObject object=new WXTextObject();
				object.text=Content;
				WXMediaMessage msg=new WXMediaMessage();
				msg.mediaObject=object;
				msg.description=Content;
				SendMessageToWX.Req req=new SendMessageToWX.Req();
				req.scene=req.WXSceneTimeline;
				req.transaction=String.valueOf(System.currentTimeMillis());
				req.message=msg;
				api.sendReq(req);
			}
		});
	}
  
	
	//内部类
	 class TimeLineAdapter extends BaseAdapter
	 {
	  Context context;
	  List<HashMap<String, String>> lsHashData;
	  Handler handler;
	  public TimeLineAdapter(Context context,Handler handler,List<HashMap<String, String>> data)
	  {
		  this.handler=handler;
		  this.context=context;
		  this.lsHashData=data;
	  }
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return lsHashData.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@SuppressLint({ "NewApi", "InlinedApi" })
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			{
				if(position==3)
				{
					System.out.println("");
				}
				if(convertView==null)
				{
		      	convertView=LayoutInflater.from(context).inflate
				    (R.layout.statusitem,null);
				}
				LinearLayout llUser =(LinearLayout)convertView.findViewById(R.id.lluser);
			TextView tvUsername=(TextView)convertView.findViewById(R.id.tvusername);
			TextView tvcretime=(TextView)convertView.findViewById(R.id.tvcretime);
			TextView tvsource=(TextView)convertView.findViewById(R.id.tvsource);
			final TextView tvstatusattitude=(TextView)convertView.findViewById(R.id.tvstatusattitude);
			final TextView tvstatuscomment=(TextView)convertView.findViewById(R.id.tvstatuscomment);
			final TextView tvstatusreposts=(TextView)convertView.findViewById(R.id.tvstatusreposts);
			TextView tvstatustext=(TextView)convertView.findViewById(R.id.tvstatustext);
			TextView tvretstatustext=(TextView)convertView.findViewById(R.id.tvretstatustext);
			
			String tid=((String)lsHashData.get(position).get("resource"))+"_"+((String)lsHashData.get(position).get("id"));
		    List<byte[]> tempList = mapImgList.get(tid);
		    List<String> ttypeList = mapTypeList.get(tid);
			TableLayout tableLayout =(TableLayout)convertView.findViewById(R.id.tlPics);
			tableLayout.removeAllViews();
		    if(tempList.size()>0)
			{
		    	WindowManager wm = ((Activity)context).getWindowManager();
		    	int width = wm.getDefaultDisplay().getWidth();
		    	
				TableRow row=null;
		    for(int i=0;i<tempList.size();i++)
			{
		    	if(i%3==0)
		    	{
		    		row=new TableRow(context);
		    		row.setGravity(Gravity.CENTER);
		    	}
		    	if(true)
		    	{
				ImageView view = new ImageView(context);
				view.setPadding(5, 5, 5, 5);
				if(tempList.get(i)!=null)
				{

					Bitmap mBitmap =ImageFactory.scaleImg( width/3-10,  width/3-10, FormatTools.getInstance().Bytes2Bitmap(tempList.get(i)));
					
				//Drawable zoomDrawable=ModifyDrawableScale.zoomDrawable(FormatTools.getInstance().Bytes2Drawable(tempRetList.get(i)), ModifyDrawableScale.dip2px(context, width/3));
				//view.setImageDrawable(FormatTools.getInstance().Bytes2Drawable(tempRetList.get(i)));
				view.setImageBitmap(mBitmap);
                 
				}
				else
				{
					view.setImageBitmap(loading);
				}
				row.addView(view);
				/*TextView textView=new TextView(context);
				textView.setMaxWidth(10);
				textView.setMinWidth(10);
				row.addView(textView);*/
		    	}
		    	else
		    	{
		    		//com.ant.liao.GifView view=new GifView(context,new ByteArrayInputStream(tempList.get(i)));
					GifView view =new GifView(context);
					view.setGifImage(tempList.get(i) );
		    		row.addView(view);
		    	}
				if((i%3==2)||(i==tempList.size()-1))
				{
					if(i==tempList.size()-1&&i%3!=2)
					{
						for(int j=0;j<(2-(i%3));j++)
						{
							ImageView view1 = new ImageView(context);
							row.addView(view1);
						}
					}
					
					tableLayout.addView(row);
					/*TextView textView1=new TextView(context);
					textView1.setMaxHeight(10);
					textView1.setMinHeight(10);
					tableLayout.addView(textView1);*/
				}
			}
			}
		    
		    tableLayout.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					if(lsHashData.get(position).get("resource").equals("Renn"))
					{
						return;
					}
					Intent intent =new Intent(context,WeiBoDetailActivity.class);
					intent.putExtra("weiboID", lsHashData.get(position).get("id"));
					intent.putExtra("resource", lsHashData.get(position).get("resource"));
					context.startActivity(intent);
					
				}
			});
		    String retid=lsHashData.get(position).get("resource")+"_"+lsHashData.get(position).get("retweeted_statusid");
		    List<byte[]> tempRetList = mapImgList.get(retid);
		    List<String> rettypeList = mapTypeList.get(retid);
		    TableLayout tableRetLayout =(TableLayout)convertView.findViewById(R.id.tlretPics);
		    tableRetLayout.removeAllViews();
		    if(tempRetList!=null&&tempRetList.size()>0)
			{
		    	WindowManager wm = ((Activity)context).getWindowManager();
		    	int width = wm.getDefaultDisplay().getWidth();
		    	
				TableRow row=null;
		    for(int i=0;i<tempRetList.size();i++)
			{
		    	if(i%3==0)
		    	{
		    		row=new TableRow(context);
		    		row.setGravity(Gravity.CENTER);
		    	}
		    	if(true)
		    	{
				ImageView view = new ImageView(context);
				if(tempRetList.get(i)!=null)
				{
					Bitmap mBitmap =ImageFactory.scaleImg( width/3-10,  width/3-10, FormatTools.getInstance().Bytes2Bitmap(tempRetList.get(i)));
					
					//Drawable zoomDrawable=ModifyDrawableScale.zoomDrawable(FormatTools.getInstance().Bytes2Drawable(tempRetList.get(i)), ModifyDrawableScale.dip2px(context, width/3));
					//view.setImageDrawable(FormatTools.getInstance().Bytes2Drawable(tempRetList.get(i)));
					view.setImageBitmap(mBitmap);
				}
				else
				{
                   view.setImageBitmap(loading);
				}
				row.addView(view);
				TextView textView=new TextView(context);
				textView.setMaxWidth(10);
				textView.setMinWidth(10);
				row.addView(textView);
		    	}
		    	else
		    	{
		    		GifView view =new GifView(context);
					view.setGifImage(tempRetList.get(i) );
		    		row.addView(view);
		    	}
				if((i%3==2)||(i==tempRetList.size()-1))
				{
					if(i==tempRetList.size()-1&&i%3!=2)
					{
						for(int j=0;j<(2-(i%3));j++)
						{
							ImageView view1 = new ImageView(context);
							row.addView(view1);
						}
					}
					tableRetLayout.addView(row);
					TextView textView1=new TextView(context);
					textView1.setMaxHeight(10);
					textView1.setMinHeight(10);
					tableRetLayout.addView(textView1);
				}
			}
			}
		    
		    tableRetLayout.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					if(lsHashData.get(position).get("resource").equals("Renn"))
					{
						return;
					}
					Intent intent =new Intent(context,WeiBoDetailActivity.class);
					intent.putExtra("weiboID", lsHashData.get(position).get("retweeted_statusid"));
					intent.putExtra("resource", lsHashData.get(position).get("resource"));
					context.startActivity(intent);
					
				}
			});
			if(lsHashData.get(position).get("resource").equals("QQ"))
			{
				ImageView ivResource=(ImageView)convertView.findViewById(R.id.ivResource); 
				ivResource.setImageResource(R.drawable.qq_icon);
			}
			else if(lsHashData.get(position).get("resource").equals("sina"))
			{
				ImageView ivResource=(ImageView)convertView.findViewById(R.id.ivResource); 
				ivResource.setImageResource(R.drawable.ic_com_sina_weibo_sdk_logo);
			}
			else if(lsHashData.get(position).get("resource").equals("Renn"))
			{
				ImageView ivResource=(ImageView)convertView.findViewById(R.id.ivResource); 
				ivResource.setImageResource(R.drawable.renren_logo);
			}
			else if(lsHashData.get(position).get("resource").equals("netease"))
			{
				ImageView ivResource=(ImageView)convertView.findViewById(R.id.ivResource); 
				ivResource.setImageResource(R.drawable.net_logo);
			}
			else if(lsHashData.get(position).get("resource").equals("sohu"))
			{
				ImageView ivResource=(ImageView)convertView.findViewById(R.id.ivResource); 
				ivResource.setImageResource(R.drawable.sohu_logo);
			}
			//new String[]{"created_at","userscreen_name","source","text","reposts_count","comments_count","attitudes_count","profile_image_url"},
			//new int[]{R.id.tvcretime,R.id.tvusername,R.id.tvsource,R.id.tvstatustext,R.id.tvstatusreposts,R.id.tvstatuscomment,R.id.tvstatusattitude,R.id.ivuserhead
			LinearLayout llret=(LinearLayout)convertView.findViewById(R.id.llretstatus);
			if(lsHashData.get(position).get("retweeted_statustext")!=null)
			{
				llret.setVisibility(View.VISIBLE);
				String content =lsHashData.get(position).get("retweeted_statususerscreen_name")+":"+lsHashData.get(position).get("retweeted_statustext");
				StatusTextProcess.setText(context,tvretstatustext,"@"+lsHashData.get(position).get("retweeted_statususerscreen_name")+" :"+lsHashData.get(position).get("retweeted_statustext"),lsHashData.get(position).get("retweeted_statusid"),lsHashData.get(position).get("resource"));
				
			}
			else
			{
				llret.setVisibility(View.GONE);
			}
			tvUsername.setText(lsHashData.get(position).get("userscreen_name"));
			tvcretime.setText(lsHashData.get(position).get("created_at"));
			tvsource.setText(lsHashData.get(position).get("source"));
			StatusTextProcess.setText(context, tvstatustext,lsHashData.get(position).get("text"),lsHashData.get(position).get("id"),lsHashData.get(position).get("resource"));
			tvstatusreposts.setText(lsHashData.get(position).get("reposts_count"));
			tvstatuscomment.setText(lsHashData.get(position).get("comments_count"));
			tvstatusattitude.setText(lsHashData.get(position).get("attitudes_count"));
			llUser.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					if(lsHashData.get(position).get("resource").equals("Renn"))
					{
						return;
					}
					Intent intent=new Intent();
					intent.setClass(context, HomeActivity.class);
					intent.putExtra("activity_type", lsHashData.get(position).get("resource"));
					intent.putExtra("uid", lsHashData.get(position).get("userid"));
						
					    context.startActivity(intent);
				}
			});
			tvstatusattitude.setOnClickListener(new TextView.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					String attitude = tvstatusattitude.getText().toString();
					int sIndex=attitude.indexOf('（');
					int eIndex=attitude.indexOf('）');
					attitude=attitude.substring(sIndex+1,eIndex);
					attitude = Integer.parseInt(attitude)+1+"";
					attitude="赞（"+attitude+"）";
					tvstatusattitude.setText(attitude);
					
				}
			});
			tvstatuscomment.setOnClickListener(new TextView.OnClickListener() {

				
				@Override
				public void onClick(View arg0) {
					final View view=LayoutInflater.from(context).inflate
							(R.layout.dlg_comment,null );
					final AlertDialog dlg = new AlertDialog.Builder(((FriLineActivity)context).getParent()).create();
					dlg.setView(view);
					Button btComment=(Button)view.findViewById(R.id.btComment);
					btComment.setOnClickListener(new Button.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							
							final EditText etContent=(EditText)view.findViewById(R.id.etCommentText);
							final CheckBox cbISRepost=(CheckBox)view.findViewById(R.id.cbIsRepost);
							String content =etContent.getText().toString() ;
							if(content.trim().equals(""))
							{
								Toast.makeText(context, "评论内容不能为空", 1000).show();
								return;
							}
							String comment =lsHashData.get(position).get("comments_count");
							int sIndex=comment.indexOf('（');
							int eIndex=comment.indexOf('）');
							comment=comment.substring(sIndex+1,eIndex);
							comment = Integer.parseInt(comment)+1+"";
							comment="评论（"+comment+"）";
							lsHashData.get(position).put("comments_count",comment);
							if(cbISRepost.isChecked() )
					    	{
								String repost =lsHashData.get(position).get("reposts_count");
								int sIndex1=repost.indexOf('（');
								int eIndex1=repost.indexOf('）');
								repost=repost.substring(sIndex1+1,eIndex1);
								repost = Integer.parseInt(repost)+1+"";
								repost="评论（"+repost+"）";
								lsHashData.get(position).put("reposts_count",repost);
					    	}
							adapter.notifyDataSetChanged();
							if(lsHashData.get(position).get("resource").equals("sina"))
							{
								if(cbISRepost.isChecked() )
						    	{
						    	SinaAPI.repost(handler ,Long.parseLong(lsHashData.get(position).get("id")), content, false);
							    }
							    SinaAPI.comment(handler, Long.parseLong(lsHashData.get(position).get("id")), content);
							}
							else if(lsHashData.get(position).get("resource").equals("QQ"))
							{
								if(cbISRepost.isChecked() )
						    	{
						    	QQAPI.repost(context ,lsHashData.get(position).get("id"), content,handler);
							    }
								else
								{
							     QQAPI.comment(context, lsHashData.get(position).get("id"), content,handler);
								}
							}
							else if(lsHashData.get(position).get("resource").equals("Renn"))
							{
								if(cbISRepost.isChecked() )
						    	{
									 RennAPI.comment(handler,content,Long.parseLong(lsHashData.get(position).get("id")));
						    	RennAPI.share(handler,content,Long.parseLong(lsHashData.get(position).get("id")));
							    }
								else
								{
							     RennAPI.comment(handler,content,Long.parseLong(lsHashData.get(position).get("id")));
								}
								}
							else if(lsHashData.get(position).get("resource").equals("netease"))
							{
								if(cbISRepost.isChecked())
							    {
									NetAPI.comment(content, lsHashData.get(position).get("id"), "1", handler);
							    }
								else
								{
									NetAPI.comment(content, lsHashData.get(position).get("id"), "0", handler);
								}
							}
							else if(lsHashData.get(position).get("resource").equals("sohu"))
							{
								if(cbISRepost.isChecked())
							    {
									SohuWeiboAPI.repost(content, lsHashData.get(position).get("id"), handler);
							    }
								SohuWeiboAPI.comment(content,  lsHashData.get(position).get("id"), handler);
							}
							dlg.dismiss();
						}
					});
	                Button btCancel=(Button)view.findViewById(R.id.btCancel);
					
					btCancel.setOnClickListener(new Button.OnClickListener() {
						
						@Override
						public void onClick(View v) {
						dlg.cancel();
						}
					});
				    dlg.show();
				}
				
			}) ;

			
	        tvstatusreposts.setOnClickListener(new TextView.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					View view=LayoutInflater.from(context).inflate
							(R.layout.dlg_repost,null );
					TextView tvSourceUser=(TextView)view.findViewById(R.id.tvsourceuser);
					final EditText etContent=(EditText)view.findViewById(R.id.etRepostText);
					final CheckBox cbISComment=(CheckBox)view.findViewById(R.id.cbIsComment);
					
					final AlertDialog dlg = new AlertDialog.Builder(((FriLineActivity)context).getParent()).create();
					dlg.setView(view);
					
					
					Button btRepost=(Button)view.findViewById(R.id.btRepost);
					
					btRepost.setOnClickListener(new Button.OnClickListener() {
						
						@Override
						public void onClick(View v) {
						String content =etContent.getText().toString() ;
						String repost =lsHashData.get(position).get("reposts_count");
						int sIndex1=repost.indexOf('（');
						int eIndex1=repost.indexOf('）');
						repost=repost.substring(sIndex1+1,eIndex1);
						repost = Integer.parseInt(repost)+1+"";
						repost="评论（"+repost+"）";
						lsHashData.get(position).put("reposts_count",repost);
						boolean isComment =cbISComment.isChecked();
						if(isComment)
						{
							String comment =lsHashData.get(position).get("comments_count");
							int sIndex=comment.indexOf('（');
							int eIndex=comment.indexOf('）');
							comment=comment.substring(sIndex+1,eIndex);
							comment = Integer.parseInt(comment)+1+"";
							comment="评论（"+comment+"）";
							lsHashData.get(position).put("comments_count",comment);
						}
						adapter.notifyDataSetChanged();
						if(lsHashData.get(position).get("resource").equals("sina"))
						{
						SinaAPI.repost(handler ,Long.parseLong(lsHashData.get(position).get("id")), content, isComment);
						}
						else if(lsHashData.get(position).get("resource").equals("QQ"))
						{
							QQAPI.repost(context, lsHashData.get(position).get("id"), content,handler);
						}
						else if(lsHashData.get(position).get("resource").equals("Renn"))
						{
							RennAPI.share(handler, content, Long.parseLong(lsHashData.get(position).get("id")));
							if(isComment)
								RennAPI.comment(handler, content, Long.parseLong(lsHashData.get(position).get("id")));
						}
						else if(lsHashData.get(position).get("resource").equals("netease"))
						{
							if(isComment)
						    {
								NetAPI.repost(content, lsHashData.get(position).get("id"), "1", handler);
						    }
							else
							{
								NetAPI.repost(content, lsHashData.get(position).get("id"), "0", handler);
							}
						}
						else if(lsHashData.get(position).get("resource").equals("sohu"))
						{
							SohuWeiboAPI.repost(content, lsHashData.get(position).get("id"), handler);
							if(isComment)
						    {
								SohuWeiboAPI.comment(content, lsHashData.get(position).get("id"), handler);
						    }
						}
						dlg.cancel();
						}
					});
	                Button btCancel=(Button)view.findViewById(R.id.btCancel);
					
					btCancel.setOnClickListener(new Button.OnClickListener() {
						
						@Override
						public void onClick(View v) {
						dlg.cancel();
						}
					});
					dlg.show();
					tvSourceUser.setText(lsHashData.get(position).get("userscreen_name"));
					
				}
			});
			}
			String headid=lsHashData.get(position).get("resource")+lsHashData.get(position).get("id");
			if(mapHeadImgList.get(headid)!=null)
			{
				ImageView ivUserHead =(ImageView) convertView.findViewById(R.id.ivuserhead);
				ivUserHead.setImageDrawable(mapHeadImgList.get(headid));
			}
			else
			{
				ImageView ivUserHead =(ImageView) convertView.findViewById(R.id.ivuserhead);
				ivUserHead.setImageResource(R.drawable.nohead);
			}
			return convertView;
		}
		
	 }
	 
	

	
	
}

class StatusListComparator implements Comparator<HashMap<String,String>>
{

	@Override
	public int compare(HashMap<String, String> lhs, HashMap<String, String> rhs) {
		return rhs.get("timestamp").compareTo(lhs.get("timestamp"));
	}
	 
}


	class ModifyDrawableScale
	{
		static Bitmap drawableToBitmap(Drawable drawable)// drawable 转换成bitmap
	    {
	              int width = drawable.getIntrinsicWidth();   // 取drawable的长宽
	              int height = drawable.getIntrinsicHeight();
	            Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888:Bitmap.Config.RGB_565;         // 取drawable的颜色格式
	              Bitmap bitmap = Bitmap.createBitmap(width, height, config);     // 建立对应bitmap
	              Canvas canvas = new Canvas(bitmap);         // 建立对应bitmap的画布
	              drawable.setBounds(0, 0, width, height);
	              drawable.draw(canvas);      // 把drawable内容画到画布中
	              return bitmap;
	    }

	    @SuppressWarnings("deprecation")
		static Drawable zoomDrawable(Drawable drawable, int w)
	    {
	              int width = drawable.getIntrinsicWidth();
	              int height= drawable.getIntrinsicHeight();
	              double newh = (((double)height)/((double)width))*((double)w);
	              int h=(int)newh;
	              Bitmap oldbmp = drawableToBitmap(drawable);// drawable转换成bitmap
	              Matrix matrix = new Matrix();   // 创建操作图片用的Matrix对象
	              float scaleWidth = ((float)w / width);   // 计算缩放比例
	              float scaleHeight = ((float)h / height);
	              matrix.postScale(scaleWidth, scaleHeight);         // 设置缩放比例
	              Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height, matrix, true);       // 建立新的bitmap，其内容是对原bitmap的缩放后的图
	              return new BitmapDrawable(newbmp);       // 把bitmap转换成并返回
	    }
	    
	    public static int px2dip(Context context, float pxValue) {  
	        final float scale = context.getResources().getDisplayMetrics().density;  
	        return (int) (pxValue / scale + 0.5f);  
	    } 
	    /** 
	     * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 
	     */  
	    public static int dip2px(Context context, float dpValue) {  
	        final float scale = context.getResources().getDisplayMetrics().density;  
	        return (int) (dpValue * scale + 0.5f);  
	    }  
	}
